from django.template import Context, loader
from knowledgebase.models import KnowledgeDataBase, Formula
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import get_object_or_404, render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from polls.models import Choice, Pol

def index(request):
    all = KnowledgeDataBase.objects.all()
    t = loader.get_template('knowledgebase/index.html')
    c = Context({
        'kbs': all,
    })
    return HttpResponse(t.render(c))


def fromulaForm(requets):
    kbs  = KnowledgeDataBase.objects.all()
    return render_to_response('knowledgebase/addFormula.html', {'kbs': kbs},
                               context_instance=RequestContext(request))


def addFormula(request):
    try:
        kb = get_object_or_404(KnowledgeDataBase, pk=request.POST['knwoledgebase'])
        
        f = Formula()
        f.body = request.POST['formulaBody']
        
    except (KeyError, Choice.DoesNotExist):
        # Redisplay the poll voting form.
        return render_to_response('knowledgebase/addFormula.html', {
            'kbs'  : KnowledgeDataBase.objects.all(),
            'error_message': "You didn't select a choice.",
        }, context_instance=RequestContext(request))
    else:
        selected_choice.votes += 1
        selected_choice.save()
        # Always return an HttpResponseRedirect after successfully dealing
        # with POST data. This prevents data from being posted twice if a
        # user hits the Back button.
        return HttpResponseRedirect(reverse('polls.views.results', args=(p.id,)))
